package com.demo.mqtt.common.client;

import com.demo.mqtt.zigbee.handeler.Handeler;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @program: mqtt-demo
 * @description: 消息回调
 * @author: liuYunKai
 * @create: 2021-03-23 13:03
 */
@Component
public class MessageCallback implements MqttCallback {

    @Autowired
    private Handeler handeler;

    private Logger log = LoggerFactory.getLogger(MessageCallback.class);


    @Override
    public void connectionLost(Throwable throwable) {

        //丢失对服务端的连接后触发该方法回调。
        //此处可以做一些特殊处理，比如重连
        log.info("丢失了对broker的连接");

    }

    /**
     * 订阅到消息后的回调
     * 该方法由mqtt客户端同步调用，在此方法未正确返回前，不会发送ack确认消息到broker
     * 一旦该方法向外抛出了异常，客户端将异常关闭。
     * 当再次连接时，所有QoS1、QoS2且客户端未进行ack确认的消息都会由broker服务器再次发送到客户端
     *
     * @param topic
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        log.info("订阅到消息，topic={},message={},qos={},msg={}",
                topic, mqttMessage.getId(), mqttMessage.getQos(), new String(mqttMessage.getPayload()));


        handeler.payloadHandel(topic, mqttMessage);
    }

    /**
     * 消息发布完成且收到ack确认后的回调
     * QoS0: 消息被网络发出后触发一次
     * QoS1: 当收到broker的PUBACK消息后触发
     * QoS2: 当收到broker的PUBCOMP消息后触发
     * @param token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

        int messageId = token.getMessageId();

        String[] topics = token.getTopics();

        log.info("消息发送完成，messageId={}，topics={}",messageId,topics);

    }
}
